<template>
  <div class="backups-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据库备份管理</span>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建备份
          </el-button>
        </div>
      </template>

      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="filename" label="文件名" show-overflow-tooltip />
        <el-table-column prop="size" label="文件大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleDownload(row)">
              下载
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建备份对话框 -->
    <el-dialog v-model="createVisible" title="创建备份" width="500px">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="备份描述">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入备份描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCreate" :loading="createLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getBackupList,
  createBackup,
  deleteBackup,
  type BackupData,
  type CreateBackupParams
} from '@/api/backups'
import { formatDate, utils } from '@/utils'

const loading = ref(false)
const createVisible = ref(false)
const createLoading = ref(false)

const tableData = ref<BackupData[]>([])

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const createForm = reactive<CreateBackupParams>({
  description: ''
})

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  return utils.formatFileSize(bytes)
}

// 加载备份列表
const loadBackupList = async () => {
  loading.value = true
  try {
    const res = await getBackupList({
      page: pagination.page,
      pageSize: pagination.size
    })
    tableData.value = res.data.list
    pagination.total = res.data.total
    pagination.page = res.data.page
    pagination.size = res.data.pageSize
  } catch (error: any) {
    ElMessage.error(error.message || '加载备份列表失败')
  } finally {
    loading.value = false
  }
}

// 创建备份
const handleCreate = () => {
  createVisible.value = true
  createForm.description = ''
}

// 确认创建备份
const confirmCreate = async () => {
  createLoading.value = true
  try {
    const params: CreateBackupParams = {}
    if (createForm.description) {
      params.description = createForm.description
    }
    await createBackup(params)
    ElMessage.success('备份创建成功')
    createVisible.value = false
    loadBackupList()
  } catch (error: any) {
    ElMessage.error(error.message || '创建备份失败')
  } finally {
    createLoading.value = false
  }
}

// 下载备份
const handleDownload = async (row: BackupData) => {
  try {
    loading.value = true
    
    // 使用 axios 直接请求，以便获取响应头
    const axios = (await import('axios')).default
    const token = localStorage.getItem('portal-admin-token')
    const baseURL = import.meta.env.VITE_API_BASE_URL || '/api'
    
    const response = await axios.post(
      `${baseURL}/backups/download`,
      { id: row.id },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : ''
        },
        responseType: 'blob',
        timeout: 60000
      }
    )
    
    // 检查响应是否为错误
    if (response.data.type === 'application/json') {
      const text = await response.data.text()
      const errorData = JSON.parse(text)
      throw new Error(errorData.message || '下载失败')
    }
    
    // 从响应头获取文件名
    const contentDisposition = response.headers['content-disposition']
    let filename = row.filename || `backup_${row.id}.sql`
    
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, '')
        // 处理 URL 编码的文件名
        try {
          filename = decodeURIComponent(filename)
        } catch {
          // 如果解码失败，使用原始文件名
        }
      }
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(response.data)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    
    // 清理
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
    
    ElMessage.success('下载成功')
  } catch (error: any) {
    console.error('下载失败:', error)
    
    // 如果是 blob 类型的错误响应，尝试解析错误信息
    if (error.response?.data instanceof Blob && error.response.data.type === 'application/json') {
      try {
        const text = await error.response.data.text()
        const errorData = JSON.parse(text)
        ElMessage.error(errorData.message || '下载失败')
      } catch {
        ElMessage.error('下载失败')
      }
    } else {
      ElMessage.error(error.message || '下载失败')
    }
  } finally {
    loading.value = false
  }
}

// 删除备份
const handleDelete = (row: BackupData) => {
  ElMessageBox.confirm(`确定要删除备份 "${row.filename}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteBackup({ id: row.id })
        ElMessage.success('删除成功')
        loadBackupList()
      } catch (error: any) {
        ElMessage.error(error.message || '删除失败')
      }
    })
    .catch(() => {})
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadBackupList()
}

// 页码改变
const handlePageChange = (page: number) => {
  pagination.page = page
  loadBackupList()
}

onMounted(() => {
  loadBackupList()
})
</script>

<style scoped lang="scss">
.backups-page {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

